package com.example.forwardmessages

import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.text.SimpleDateFormat
import java.util.*
import java.util.Properties
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
import com.example.forwardmessages.AppConfig
import com.example.forwardmessages.SmsMessage as AppSmsMessage

class SmsForwardWorker(context: Context, workerParams: WorkerParameters)
    : Worker(context, workerParams) {

    companion object {
        private const val TAG = "SmsForwardWorker"
        const val KEY_SENDER = "sender"
        const val KEY_CONTENT = "content"
        const val KEY_TIME = "time"
        const val KEY_SIM_INFO = "simInfo"
    }
    
    /**
      * 获取设备上最近的若干条短信
      */
     private fun getRecentSmsMessages(context: Context, count: Int): List<AppSmsMessage> {
         val recentSmsList = mutableListOf<AppSmsMessage>()
        
        try {
            // 查询最近的短信
            val uri = android.net.Uri.parse("content://sms/inbox")
            val projection = arrayOf("_id", "address", "body", "date", "read")
            val sortOrder = "date DESC"
            
            // 执行查询
            context.contentResolver.query(
                uri,
                projection,
                null,
                null,
                "$sortOrder LIMIT $count"
            )?.use { cursor ->
                if (cursor.moveToFirst()) {
                    do {
                        // 获取短信数据
                        val id = cursor.getString(cursor.getColumnIndexOrThrow("_id"))
                        val address = cursor.getString(cursor.getColumnIndexOrThrow("address"))
                        val body = cursor.getString(cursor.getColumnIndexOrThrow("body"))
                        val date = cursor.getLong(cursor.getColumnIndexOrThrow("date"))
                        val read = cursor.getInt(cursor.getColumnIndexOrThrow("read"))
                        
                        // 创建AppSmsMessage对象并添加到列表
                        recentSmsList.add(AppSmsMessage(id, address, body, date, read))
                    } while (cursor.moveToNext())
                }
            }
            
            Log.d(TAG, "成功获取最近${recentSmsList.size}条短信")
        } catch (e: Exception) {
            Log.e(TAG, "获取最近短信失败: ${e.message}", e)
        }
        
        return recentSmsList
    }

    override fun doWork(): Result {
        try {
            // 从输入参数获取短信信息
            val sender = inputData.getString(KEY_SENDER)
            val content = inputData.getString(KEY_CONTENT)
            val time = inputData.getString(KEY_TIME)
            val simInfo = inputData.getString(KEY_SIM_INFO)

            if (sender.isNullOrEmpty() || content.isNullOrEmpty()) {
                Log.e(TAG, "无效的短信数据")
                // 记录错误到持久化存储
                val notificationHelper = NotificationHelper(applicationContext)
                notificationHelper.showErrorNotification("SmsForwardWorker", "无效的短信数据")
                return Result.failure()
            }

            // 获取应用配置
            val appConfig = AppConfig(applicationContext)
            val smtpServer = appConfig.smtpServer
            val smtpPort = appConfig.smtpPort
            val emailUser = appConfig.emailUser
            val emailPassword = appConfig.emailPassword
            val recipientEmail = appConfig.recipientEmail

            // 检查必要的邮箱配置
            if (!appConfig.isEmailConfigComplete()) {
                Log.e(TAG, "邮箱配置不完整")
                // 显示通知提醒用户配置邮箱
                val notificationHelper = NotificationHelper(applicationContext)
                notificationHelper.showErrorNotification("SmsForwardWorker", "邮箱配置不完整，请在应用中配置SMTP信息")
                return Result.failure()
            }

            // 构建邮件内容
            val emailSubject = "[新短信] 来自 $sender 的消息"
            var emailBody = buildEmailBody(sender, content, time, simInfo)

            // 获取是哪张SIM卡的新消息
            val simCardUsed = simInfo ?: "未知SIM卡"
            Log.d(TAG, "当前使用的SIM卡: $simCardUsed")

            // 根据SIM卡选择不同的收件人邮箱
            val targetRecipientEmail = appConfig.getRecipientEmailBySimInfo(simCardUsed)
            Log.d(TAG, "根据SIM卡选择的收件人邮箱: $targetRecipientEmail")

            // 获取最新近10条消息
            val recentSmsList = getRecentSmsMessages(applicationContext, 50)
            if (recentSmsList.isNotEmpty()) {
                // 如果有最近的短信，添加到邮件正文
                val recentSmsText = StringBuilder()
                recentSmsText.append("\n\n最近10条短信:\n")
                recentSmsText.append("------------------------\n")
                
                recentSmsList.forEachIndexed { index, sms ->
                    recentSmsText.append("${index + 1}. 发送者: ${sms.address}\n")
                    recentSmsText.append("   时间: ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date(sms.date))}\n")
                    recentSmsText.append("   内容: ${sms.body}\n")
                    recentSmsText.append("------------------------\n")
                }
                
                emailBody += recentSmsText.toString()
            }

            // 发送邮件
            sendEmail(smtpServer, smtpPort, emailUser, emailPassword, targetRecipientEmail, emailSubject, emailBody)

            Log.d(TAG, "邮件发送成功")
            return Result.success()

        } catch (e: Exception) {
            Log.e(TAG, "邮件发送失败: ${e.message}", e)
            
            // 显示错误通知，让用户知道邮件发送失败
            val notificationHelper = NotificationHelper(applicationContext)
            notificationHelper.showErrorNotification("SmsForwardWorker", "短信转发失败: ${e.message ?: "未知错误"}", e)
            
            // 如果失败，WorkManager会根据配置自动重试
            return Result.retry()
        }
    }

    private fun buildEmailBody(sender: String, content: String, time: String?, simInfo: String?): String {
        val body = StringBuilder()
        body.append("发件人: $sender\n")
        time?.let { body.append("时间: $it\n") }
        simInfo?.let { body.append("SIM卡: $it\n") }
        body.append("\n\n短信内容:\n")
        body.append(content)
        return body.toString()
    }

    private fun sendEmail(
        smtpServer: String,
        smtpPort: Int,
        emailUser: String,
        emailPassword: String,
        recipientEmail: String,
        subject: String,
        body: String
    ) {
        // 设置邮件属性
        val props = Properties()
        props["mail.smtp.host"] = smtpServer
        props["mail.smtp.port"] = smtpPort.toString()
        props["mail.smtp.auth"] = "true"
        props["mail.smtp.starttls.enable"] = "true"

        // 创建会话
        val session = Session.getInstance(props, object : Authenticator() {
            override fun getPasswordAuthentication(): PasswordAuthentication {
                return PasswordAuthentication(emailUser, emailPassword)
            }
        })

        // 创建并发送邮件
        val message = MimeMessage(session)
        message.setFrom(InternetAddress(emailUser))
        message.addRecipient(Message.RecipientType.TO, InternetAddress(recipientEmail))
        message.subject = subject
        message.setText(body)

        Transport.send(message)
    }
}